package com.mxx.mxx.service.impl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mxx.mxx.common.core.domain.AjaxResult;
import com.mxx.mxx.common.core.domain.entity.SysUser;
import com.mxx.mxx.common.core.domain.model.LoginUser;
import com.mxx.mxx.common.enums.UserType;
import com.mxx.mxx.common.service.TokenService;
import com.mxx.mxx.dto.AccountDTO;
import com.mxx.mxx.dto.AccountUpdateDTO;
import com.mxx.mxx.mapper.AccountMapper;
import com.mxx.mxx.po.Account;
import com.mxx.mxx.service.IAccountService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dronff
 * @since 2024-04-19
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {
    @Resource
    private TokenService tokenService;
    @Resource
    private SnowflakeGenerator snowflakeGenerator;
    public AjaxResult getToken(String phoneNumber, String password) {
        // 获取账户
        QueryWrapper<Account> qo = new QueryWrapper<Account>()
                .eq("phone_number", phoneNumber)
                .eq("password", password);
        Account account = getOne(qo);
        if (Objects.isNull(account)) {
            return AjaxResult.error("账户或密码错误");
        }
        SysUser sysUser = SysUser.builder()
                .userType(UserType.USER)
                .userInfo(account)
                .build();
        LoginUser loginUser = LoginUser.builder()
                .user(sysUser)
                .build();
        String token = tokenService.createToken(loginUser);
        return AjaxResult.success("登录成功", token);
    }

    @Override
    public AjaxResult add(AccountDTO account) {
        if (getOne(
                new QueryWrapper<Account>()
                        .eq("phone_number", account.getPhoneNumber())
        ) != null) {
            return AjaxResult.error("注册失败，手机号已存在");

        }
        Account acInDb = new Account();
        BeanUtils.copyProperties(
                account,
                acInDb
        );
        acInDb.setAccountNumber(snowflakeGenerator.next());
        acInDb.setDelFlag(true);
        if(!save(acInDb)){
            return AjaxResult.error("注册失败");
        }
        return AjaxResult.success("注册成功");
    }

    @Override
    public AjaxResult updateUser(Integer userId, AccountUpdateDTO account) {
        Account byId = getById(userId);
        if (byId == null) {
            return AjaxResult.error("更新失败，账户不存在");
        }
        BeanUtils.copyProperties(account,byId );
        boolean b = updateById(byId);
        if (b) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }
}
